module(..., package.seeall)
require "pins"
require "common"
require "http"
BL = pins.setup(4, 0)
BL(0)
local poem = ""
isSleep = true
function sleep()
    if isSleep then return end
    pm.sleep("lcd_up")
    isSleep = true
    disp.sleep(1)
    BL(0)
end

function wake(f)
    if not isSleep then return end
    pm.wake("lcd_up")
    isSleep = nil
    disp.sleep(0)
    if not f then
        page.update()
    end
    BL(1)
    io.unmount(io.SDCARD)
    io.mount(io.SDCARD)
end

--rgb值转rgb565
function rgb(r, g, b)
    return (r - r % 8) / 8 * 2048 + (g - g % 4) / 4 * 32 + (b - b % 8) / 8
end

--放置文字，自动转码
function text(s, x, y, r, g, b)
    if r and g and b then
        disp.setcolor(rgb(r, g, b))
    end
    disp.puttext(common.utf8ToGb2312(s), x, y)
end

--居中显示文字
function putStringCenter(s, x, y, r, g, b)
    local str = common.utf8ToGb2312(s)
    text(s, x - str:len() * ((CHAR_WIDTH - CHAR_WIDTH % 2) / 2), y, r, g, b)
end

--靠右显示文字
function putStringRight(s, x, y, r, g, b)
    local str = common.utf8ToGb2312(s)
    text(s, x - str:len() * CHAR_WIDTH, y, r, g, b)
end

--快速计算y
function gety(l)
    return l * CHAR_WIDTH * 2
end

--快速计算x
function getx(l)
    return l * CHAR_WIDTH
end

sys.taskInit(function()
    sys.waitUntil("LCD_INIT")
    wake(1)
    CHAR_WIDTH = 16
    disp.setfontheight(32)
    disp.clear()
    for i = 1, 51 do
        local c = i * 5
        putStringCenter("欢迎使用", 120, 90, c, c, c)
        putStringCenter("X Magic Box", 120, 130, c, c, c)
        disp.update()
    end
    http.request("GET", "https://v1.hitokoto.cn/?c=i&encode=text&charset=utf-8&max_length=16", nil, nil, nil, 30000, function(result, prompt, head, body)
        if result then
            poem = body
        end
    end)
    log.info("LCD", "LCD IS finished!")
    sys.publish("START_DONE")
end)


sys.subscribe("KEY_EVENT", function(k, e)
    disp.clear()
    if k == "C" and e then
        collectgarbage("collect")
        log.info("LCD", poem)
        text(poem, 5, 6, 255, 50, 255)
        disp.update()
        http.request("GET", "https://v1.hitokoto.cn/?c=i&encode=text&charset=utf-8&max_length=16", nil, nil, nil, 30000, function(result, prompt, head, body)
            if result then
                poem = body
            end
        end)
        collectgarbage("collect")
    end
end)
